//
//  MyFirstIPhoneAppAppDelegate.m
//  MyFirstIPhoneApp
//
//  Created by Andrew Spina on 4/6/10.
//  Copyright STScI 2010. All rights reserved.
//

#import "iD20AppDelegate.h"
#import "GridController.h"

@implementation FirstGridAppAppDelegate

@synthesize window;
@synthesize navController;

#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
+ (NSManagedObjectContext *) getManagedObjectContext {
	
    if (managedObjectContext == nil) {
		managedObjectContext = [[NSManagedObjectContext alloc] init];
		[managedObjectContext setPersistentStoreCoordinator: [FirstGridAppAppDelegate getPersistentStoreCoordinator]];
    }
    return managedObjectContext;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
+ (NSPersistentStoreCoordinator *) getPersistentStoreCoordinator {
	
    if (persistentStoreCoordinator == nil) {
		NSURL *storeUrl = [NSURL fileURLWithPath: [[FirstGridAppAppDelegate applicationDocumentsDirectory] stringByAppendingPathComponent: @"iD20.sqlite"]];
		NSError *error;
		persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [FirstGridAppAppDelegate getManagedObjectModel]];
		if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
			NSLog(@"error adding persistent store");
			// Handle error
		}
	}    
    return persistentStoreCoordinator;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
+ (NSManagedObjectModel *) getManagedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]; 
    return managedObjectModel;
}

/**
 Returns the path to the application's documents directory.
 */
+ (NSString *)applicationDocumentsDirectory {
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

#pragma mark -
#pragma mark Application Lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	[window addSubview: navController.view];
	[window makeKeyAndVisible];
}

- (void)dealloc {
    
	[managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    	
    [window release];
	[navController release];
    [super dealloc];
}


@end
